package com.ck.ips.core.spring;


import com.ck.common.model.OperationResult;
import com.ck.core.util.DateUtils;
import com.ck.ips.core.config.CustomProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @Description: 自定义ControllerAdvice处理器
* @Author: hf
* @Date:    2019/4/29 15:58
* @Version: 1.0
*/
@ControllerAdvice
public class CustomControllerAdvice {
    private static Logger logger = LoggerFactory.getLogger(CustomControllerAdvice.class);
    @Autowired
    private CustomProperties customProperties;
    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd HH:mm"), true));
    }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        // 添加前端资源路径:
        model.addAttribute("staticResourceDomain", customProperties.getStaticResourceDomain());
    }

    /**
     * 全局异常捕捉处理。
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public OperationResult errorHandler(Exception ex) {
        logger.error(ex.getMessage(),ex);
        return OperationResult.newSystemErrorOperationResult();
    }

}

